local blaze = require "blaze"
local app = require "app"
local AvatarIcon = require "ui.Common.AvatarIcon"
local Emoji = require "club.threecard.gamelib.UI.Chat.Emoji"

local game = app.game.running
local get_emoji = game.config.chat.get_emoji
local log = blaze.logging.get("ChatItem")

local M = game.ui.element()

-- message 对应store.chat里的单条message
function M:ctor(message)
    self.message = message
    if message.from_self then
        self.res = "club.threecard.gamelib/ui/chat.b:ChatItem - Me"
    else
        self.res = "club.threecard.gamelib/ui/chat.b:ChatItem - Other"
    end
    self.avatar_icon = AvatarIcon.new()
    self.avatar_icon:set_player(message.sender)
    self.emoji = nil
end

function M:on_injected(bind)
    bind("gameobject.element", self.avatar_icon_obj, self.avatar_icon)

    local msg = self.message
    if msg.msg_type == game.chat.MSG_TYPE_TEXT
    or msg.msg_type == game.chat.MSG_TYPE_PHRASE then
        self.content_txt.enabled = true
        self.content_txt.text = msg.text
    elseif msg.msg_type == game.chat.MSG_TYPE_EMOJI then
        local config = get_emoji(msg.emoji_id)
        if not config then
            self.content_txt.enabled = true
            self.content_txt.text = ""
            log.warn(string.format("未知表情：%s", msg.emoji_id))
            return
        end
        self.content_txt.enabled = false
        self.emoji = Emoji.new(config)
        self.emoji:load()
        self.emoji:set_parent(self.bg_root)
    end
end

function M:on_release()
    self:super("on_release")
    self.avatar_icon:release()
    if self.emoji then
        self.emoji:release()
    end
end

return M